//
//  IGExhibitionVC.m
//  jingdongfang
//
//  Created by boectoswteam on 2018/5/7.
//  Copyright © 2018年 BOE-SBG-CTO. All rights reserved.
//圈子-活动-展览

#import "IGExhibitionVC.h"
#import "CZHNavagationBarTranslucentTool.h"
#import "IGActivityCollectionHeaderView.h"
#import "IGDrawingsCollectionCell.h"
#import "IGActivityMuseumCollectionCell.h"
#import "IGActivityDetailApi.h"
#import "IGActivityAttentionApi.h"
#import "XiangQingViewController.h"
#import "IntroViewController.h"

@interface IGExhibitionVC ()<UICollectionViewDelegateFlowLayout,UICollectionViewDataSource,UIScrollViewDelegate,UICollectionViewDelegate>

@property (nonatomic, strong) IGActivityCollectionHeaderView *headView;  //头视图
@property (nonatomic, strong) UICollectionView *contentCollectionV;
@property (nonatomic, strong) UILabel *drawingNumbersL;                //参展作品label
@property (nonatomic, strong) UIView *bottomView;                      //底部菜单栏
@property (nonatomic, strong) IGActivityDetailApi *exhibitionApi;       //展览API
@property (nonatomic, assign) NSInteger pageNumbers;                   //页数
@property (nonatomic, strong) NSMutableArray *exhibitionArray;         //参赛作品数据源
@property (nonatomic, strong) IGActivityDetailModel *model;             //整个界面数据源
@property (nonatomic, strong) IGActivityAttentionApi *attentionApi;     //关注&取消关注API
@property (nonatomic, assign) BOOL isFocused;                         //是否关注（0 已关注  1未关注）

@end

@implementation IGExhibitionVC

#pragma mark - lifeCycle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor mainBackgroundColor];
    [self ig_setupRightButtonItemWithTitle:nil image:[UIImage imageNamed:@"share_btn"] highLightedImage:[UIImage imageNamed:@"share_btn"]];
    [self initContentCollectionV];
    [self.view addSubview:self.bottomView];
    _pageNumbers = 0;
    _isFocused = 1;
    [self loadExhibitionData];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.translucent = YES;
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc]init] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc]init]];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    self.contentCollectionV.scrollEnabled = YES;
    [self scrollViewDidScroll:self.contentCollectionV];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName, [UIFont boldSystemFontOfSize:17],NSFontAttributeName,nil]];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.translucent = NO;
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:nil];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    self.contentCollectionV.scrollEnabled = NO;
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor blackColor],NSForegroundColorAttributeName, [UIFont boldSystemFontOfSize:17],NSFontAttributeName,nil]];
}

-(void)initContentCollectionV{
    _contentCollectionV = [[UICollectionView alloc]initWithFrame:CGRectMake(0, -64, KSCREENWIDTH, KSCREENHEIGHT - 44+64) collectionViewLayout:[[UICollectionViewFlowLayout alloc]init]];
    _contentCollectionV.delegate = self;
    _contentCollectionV.dataSource = self;
    _contentCollectionV.showsVerticalScrollIndicator = NO;
    _contentCollectionV.showsHorizontalScrollIndicator = NO;
    _contentCollectionV.backgroundColor = [UIColor clearColor];
    [_contentCollectionV registerClass:[IGActivityCollectionHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"IGActivityCollectionHeaderView"];
    [_contentCollectionV registerNib:[UINib nibWithNibName:@"IGActivityMuseumCollectionCell" bundle:nil] forCellWithReuseIdentifier:@"IGActivityMuseumCollectionCell"];
    [_contentCollectionV registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionReusableView"];
    [_contentCollectionV registerClass:[IGDrawingsCollectionCell class] forCellWithReuseIdentifier:@"IGDrawingsCollectionCell"];
    [self.view addSubview:_contentCollectionV];
}

-(void)loadExhibitionData{
    self.exhibitionApi = [[IGActivityDetailApi alloc]init];
    self.exhibitionApi.activityId = self.activityId;
    self.exhibitionApi.pageNumber = [NSString stringWithFormat:@"%ld",self.pageNumbers];
    self.exhibitionApi.pageSize = @"10";
    self.exhibitionApi.orderType = @"2";//最新
    self.exhibitionApi.queryTime = [self currentTimeStr];
    __weak typeof(self) weakSelf = self;
    [self.exhibitionApi startWithDecodeClass:[IGActivityDetailResponse class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
            IGActivityDetailResponse *resp = responseObject;
            IGActivityDetailModel *model = resp.data;
            weakSelf.model = resp.data;
            weakSelf.headView.data = resp.data;
            weakSelf.title = resp.data.title;
            UIButton *btn = (UIButton *)[self.bottomView viewWithTag:100];
            if ([model.focused isEqualToString:@"0"]) {
                _isFocused = 0;
                [btn setTitle:NSLocalizedString(@"已关注", nil) forState:UIControlStateNormal];
            } else {
                _isFocused = 1;
                [btn setTitle:NSLocalizedString(@"+ 关注", nil) forState:UIControlStateNormal];
            }
            weakSelf.headView.competitionBlock = ^{
                
            };
            [weakSelf.exhibitionArray addObjectsFromArray:[NSArray arrayWithArray:model.productList]];
            weakSelf.drawingNumbersL.text = [NSString stringWithFormat:@"参展作品(%lu)",(unsigned long)weakSelf.exhibitionArray.count];
            [weakSelf.contentCollectionV reloadData];
            _pageNumbers++;
            [weakSelf setupFooter];
        } else {
            [weakSelf.contentCollectionV ig_endFooterRefreshingWithNoMoreData];
        }
    }];
}

- (void)setupFooter
{
    @KWeakObj(self)
    [_contentCollectionV ig_setFooterWithRefreshingBlock:^{
        [selfWeak loadExhibitionData];
    }];
}

#pragma mark - UICollectionViewDelegateFlowLayout && UICollectionViewDataSource

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    } else {
        return self.exhibitionArray.count?self.exhibitionArray.count:0;
    }
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 2;
}

-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        if (indexPath.section == 0) {
            IGActivityCollectionHeaderView *headV = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"IGActivityCollectionHeaderView" forIndexPath:indexPath];
            headV.frame = CGRectMake(0, 0, KSCREENWIDTH, 457);
            self.headView = headV;
            headV.data = self.model;
            CGFloat height = [self getHeightWithString:self.model.activityDescription Width:KSCREENWIDTH - 30];
//            headV.frame = CGRectMake(0, 0, KSCREENWIDTH, 310+height);
            [headV setNeedsLayout];
            return headV;
        } else if (indexPath.section == 1){
            UICollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionReusableView" forIndexPath:indexPath];
            UILabel *titleLabel = [[UILabel alloc]init];
            titleLabel.frame = CGRectMake(15, 15, 200, 15);
            titleLabel.font = [UIFont boldSystemFontOfSize:16];
            self.drawingNumbersL = titleLabel;
            [view addSubview:titleLabel];
            view.backgroundColor = [UIColor whiteColor];
            return view;
        }
    }
    return nil;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        IGActivityMuseumCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"IGActivityMuseumCollectionCell" forIndexPath:indexPath];
        cell.model = self.model;
        return cell;
    } else if (indexPath.section == 1){
        IGDrawingsCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"IGDrawingsCollectionCell" forIndexPath:indexPath];
        cell.data = self.exhibitionArray[indexPath.item];
        cell.backgroundColor = [UIColor blueColor];
        [cell setNeedsLayout];
        return cell;
    }
    return nil;
}

//headerView尺寸
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    if (section == 0) {
//        if (self.model.activityDescription.length!=0) {
//            CGFloat height = [self getHeightWithString:self.model.activityDescription Width:KSCREENWIDTH - 30];
//            return CGSizeMake(KSCREENWIDTH, 310+height);
//        } else
            return CGSizeMake(KSCREENWIDTH, 457);
    } else return CGSizeMake(KSCREENWIDTH, 44);
}

//每个cell的真实尺寸
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return CGSizeMake(KSCREENWIDTH, 70);
    } else if (indexPath.section == 1){
        IGActivityDetailSingleModel *model = self.exhibitionArray[indexPath.item];
        if ([model.plates isEqualToString:@"2"]) {
            //竖版
            return CGSizeMake((KSCREENWIDTH-15)/2, ((KSCREENWIDTH-15)/2*1920/1080));
        } else {
            //横版
            return CGSizeMake((KSCREENWIDTH-15)/2, ((KSCREENWIDTH-15)/2*1080/1920));
        }
    }
    return CGSizeZero;
}

//每个item项，距离上、左、下、右的边距
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(5, 5, 5, 5);
}

//每个section中不同行之间的行间距(左右间距)
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 5;
}

//每个item之间的间距(上下间距)
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 5;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        IntroViewController *vc = [[IntroViewController alloc] init];
        vc.u_id = self.model.orgId;
        [UIViewController ig_pushViewController:vc animated:YES];
    } else if (indexPath.section == 1){
        NSLog(@"%ld-%ld",(long)indexPath.section,(long)indexPath.row);
        IGActivityDetailSingleModel *model = self.exhibitionArray[indexPath.item];
        XiangQingViewController *vc = [[XiangQingViewController alloc] init];
        vc.p_id = model.pId;
        vc.isRoot = YES;
        [UIViewController ig_pushViewController:vc animated:YES];
    }
}


#pragma mark - UIScrollViewDelegate

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat viewOffsetY = self.contentCollectionV.contentOffset.y;
    [CZHNavagationBarTranslucentTool czh_changeNavigationBarTransparencyWithViewController:self contentOffsetY:viewOffsetY];
}


#pragma mark - events

-(void)bottomBtnClicked:(UIButton *)btn{
    if (btn.tag == 100) {
        self.attentionApi = [[IGActivityAttentionApi alloc]init];
        self.attentionApi.activityId = self.activityId;
        self.attentionApi.operate = (_isFocused==0)?@"1":@"0";
        [self.attentionApi startWithDecodeClass:[IGActivityAttentionResponse class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
            IGActivityAttentionResponse *response = responseObject;
            IGBaseRespHead *head = response.resHeader;
            if ([head.code isEqualToString:@"success"]) {
                _isFocused = !_isFocused;
                if (!_isFocused) {
                    [btn setTitle:NSLocalizedString(@"已关注", nil) forState:UIControlStateNormal];
                } else if (_isFocused) [btn setTitle:NSLocalizedString(@"+ 关注", nil) forState:UIControlStateNormal];
            }
        }];
    } else if(btn.tag == 101){

    }
}

//获取当前时间戳
- (NSString *)currentTimeStr{
    NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];//获取当前时间0秒后的时间
    NSTimeInterval time=[date timeIntervalSince1970]*1000;// *1000 是精确到毫秒，不乘就是精确到秒
    NSString *timeString = [NSString stringWithFormat:@"%.0f", time];
    return timeString;
}

-(CGFloat)getHeightWithString:(NSString *)text Width:(CGFloat)width{
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc]init];
    style.lineBreakMode = NSLineBreakByWordWrapping;
    NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:15],NSParagraphStyleAttributeName:style.copy};
    CGSize size = CGSizeMake(width, 1000);
    CGFloat height = [text boundingRectWithSize:size options:NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size.height;
    return height;
}


#pragma mark - set

-(UIView *)bottomView{
    if (!_bottomView) {
        _bottomView = [[UIView alloc]init];
        _bottomView.frame = CGRectMake(0, KSCREENHEIGHT - 44, KSCREENWIDTH, 44);
        _bottomView.backgroundColor = [UIColor whiteColor];
        NSArray * titleArray = @[NSLocalizedString(@"+ 关注", nil),NSLocalizedString(@"发表评论", nil)];
        for (int i = 0; i < 2; i ++) {
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.frame = CGRectMake(KSCREENWIDTH/2*i, 0, KSCREENWIDTH/2, 44);
            [btn setTitle:titleArray[i] forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor c1Color] forState:UIControlStateNormal];
            btn.tag = 100+i;
            btn.titleLabel.font = [UIFont font16];
            [btn addTarget:self action:@selector(bottomBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
            [_bottomView addSubview:btn];
        }
        UIView *lineV = [[UIView alloc]init];
        lineV.frame = CGRectMake(KSCREENWIDTH/2 - 0.25, 10, 0.5, 24);
        lineV.backgroundColor = [UIColor c1Color];
        [_bottomView addSubview:lineV];
    }
    return _bottomView;
}

-(NSString *)activityId{
    if (!_activityId) {
        _activityId = [[NSString alloc]init];
    }
    return _activityId;
}

-(NSMutableArray *)exhibitionArray{
    if (!_exhibitionArray) {
        _exhibitionArray = [NSMutableArray array];
    }
    return _exhibitionArray;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
